package com.xxs.controller.admin;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;

import com.jfinal.aop.Before;
import com.xxs.interceptor.AdminInterceptor;
import com.xxs.utils.UUIDUtils;
import com.xxs.utils.xml.Fields;
import com.xxs.utils.xml.XmlDom4jUtils;

@Before(AdminInterceptor.class)
@SuppressWarnings("unchecked")
public class ResourceController extends BaseAdminController {
	public void list(){
    	baseList();
    	setAttr("modelName", getModeName());
    	render("list.html");
    }
	public void add(){
		String parentId = getPara(0);
		String parentName = getPara(1);
		if(parentId!=null && !parentId.equals("")){
	    	setAttr("parentId", parentId);
	    	setAttr("parentName", parentName);
			render("add.html");
		}else{
	    	render("add.html");
		}
    }
	public void save(){
    	String parentId = getPara(0);
    	if(parentId!=null && !parentId.equals("")){
    		String modelName = getModeName();
    		List<Fields> fieldList = getFields();
        	Document document = XmlDom4jUtils.getDocument(modelName);
        	List<Element> listElements = document.selectNodes("/"+modelName+"s/"+modelName+"[@id='"+parentId+"']");
        	Element element = null;
        	if(listElements!=null && listElements.size()>0){
        		element = listElements.get(0);
        		Element newElement = element.addElement(modelName);
        		for (int i = 0; i < fieldList.size(); i++) {
        			System.out.println("当前循环的属性名："+fieldList.get(i).getName()+"填充的内容"+getPara(fieldList.get(i).getName()));
        			if("id".equals(fieldList.get(i).getName())){
        				newElement.addAttribute(fieldList.get(i).getName(), UUIDUtils.creatUUID());
        			}else{
        				newElement.addAttribute(fieldList.get(i).getName(), getPara(fieldList.get(i).getName()));
        			}
        		}
            	try {
            		XmlDom4jUtils.saveDocumentToFile(modelName, document);
            	} catch (Exception e) {
            		e.printStackTrace();
            	}
        	}
    	}else{
    		baseSave();
    	}
    	list();
    }
}
